<script setup lang="ts">
import { ref } from 'vue'
import wx from 'weixin-js-sdk'

const route = useRoute()
const router = useRouter()
// console.log(route.query.date)
const showPopup = ref(false)
const isSubmit = ref()
const msg = ref()
const userInfo = useUserInfoState()
const qrCodeUrl = ref('')
const showQRCodeModal = ref(false)

const date = ref()
const money = ref()
const flag = ref(false)
const isWxConfigured = ref(false)
const isPaying = ref(false)
const timer1 = ref()
const loading = ref(false)
const showPay = ref(false)
const orderId = ref('')

const isMobile = ref(false)

// 判断是否为微信浏览器
const isWeChat = () => /MicroMessenger/i.test(navigator.userAgent)
function checkDevice() {
  const userAgent = navigator.userAgent.toLowerCase()
  // 常见的手机端的 userAgent 字符串判断
  const mobileKeywords = ['iphone', 'ipod', 'android', 'windows phone', 'blackberry', 'webos']

  isMobile.value = mobileKeywords.some(keyword => userAgent.includes(keyword))
}

onBeforeUnmount(() => {
  // 清理定时器
  if (timer1.value) {
    clearInterval(timer1.value)
  }
})
async function submitPayWx() {
  if (isPaying.value)
    return // 防止重复点击
  isPaying.value = true
  if (!orderId.value) {
    msg.value = '订单创建失败，请稍后再试'
    isSubmit.value = true
  }
  try {
    let method
    if (isMobile.value && isWeChat()) {
      method = 'mp'
    }
    else if (isMobile.value) {
      method = 'wap'
    }
    else {
      method = 'scan'
    }
    const oid = orderId.value
    const { data: res } = await useFetchPost('/api/Orders/payOrder', {
      oid,
      user_id: userInfo.value.id,
      returnurl: useRequestURL().href,
      type: 'wechat',
      method,
    })
    if (!res.value || !res.value.data) {
      msg.value = '未获取到订单信息或者订单已支付'
      isSubmit.value = true
      return
    }
    const info = res.value.data
    if (!isWxConfigured.value) {
      wx.config({
        debug: false, // 开启调试模式，调试时为true
        appId: info.appId, // 公众号的唯一标识
        timestamp: info.timeStamp, // 时间戳
        nonceStr: info.nonceStr, // 随机串
        signature: info.paySign, // 签名
        jsApiList: ['chooseWXPay'], // 需要调用的JS接口
      })
      isWxConfigured.value = true
    }

    if (isMobile.value && isWeChat()) {
      const wxReadyTimeout = setTimeout(() => {
        msg.value = '微信支付初始化失败，请刷新页面重试'
        isSubmit.value = true
        isPaying.value = false
      }, 5000)

      wx.ready(() => {
        clearTimeout(wxReadyTimeout) // 成功准备则清除
        // 调用支付接口
        wx.chooseWXPay({
          timestamp: info.timeStamp, // 支付签名时间戳
          nonceStr: info.nonceStr, // 支付签名随机串
          package: info.package, // 预支付交易会话ID
          signType: info.signType, // 签名方式，默认为'SHA1'，使用 MD5 签名时请注意
          paySign: info.paySign, // 支付签名
          success(res: any) {
            // 支付成功后的回调
            console.log('支付成功', res)
            msg.value = '祈福成功'
            isSubmit.value = true
            flag.value = true
          },
          fail(res: any) {
            // 支付失败的回调
            console.log('支付失败', res)
            msg.value = '支付失败'
            isSubmit.value = true
          },
          complete() {
            isPaying.value = false
          },
        })
      })

      wx.error((res: any) => {
        // 错误回调
        console.error('微信 SDK 错误:', res)
        msg.value = '微信支付初始化失败'
        isSubmit.value = true
        isPaying.value = false
      })
    }
    else if (isMobile.value) {
      window.location.href = info.targetUrl
    }
    else {
      // 非微信浏览器，显示二维码
      qrCodeUrl.value = info.qrCodeBase64
      showQRCodeModal.value = true
      timer1.value = setInterval(async () => {
        loading.value = true
        try {
          const { data: res } = await useFetchPost('/api/orders/getOrderInfo', {
            oid,
          })
          if (res.value.data.status == 1) {
            if (timer1.value) {
              clearInterval(timer1.value)
            }
            closeModal()
            msg.value = '祈福成功'
            isSubmit.value = true
            flag.value = true
          }
        }
        catch (error) {
          console.error('Error fetching order info:', error)
        }
        finally {
          loading.value = false
        }
      }, 1000)
    }
  }
  catch (e) {
    console.error('支付异常:', e)
    msg.value = '支付请求失败，请稍后再试'
    isSubmit.value = true
  }
  finally {
    isPaying.value = false
  }
}

async function submitPayZfb() {
  if (isPaying.value)
    return
  isPaying.value = true

  try {
    let method
    if (isMobile.value && isWeChat()) {
      method = 'mp'
    }
    else if (isMobile.value) {
      method = 'wap'
    }
    else {
      method = 'web'
    }
    const oid = orderId.value
    const { data: res } = await useFetchPost('/api/Orders/payOrder', {
      oid,
      user_id: userInfo.value.id,
      returnurl: useRequestURL().href,
      type: 'alipay',
      method,
    })

    if (!res.value || !res.value.data || !res.value.data.targetUrl) {
      msg.value = '未获取到支付信息，请稍后再试'
      isSubmit.value = true
      return
    }

    // 插入 form 并执行
    const wrapper = document.createElement('div')
    wrapper.innerHTML = res.value.data.targetUrl
    document.body.appendChild(wrapper)

    // 有些浏览器安全策略会阻止 inline script 执行，需要手动触发
    const form = wrapper.querySelector('form') as HTMLFormElement | null
    if (form) {
      form.submit()
    }
    else {
      msg.value = '支付表单解析失败'
      isSubmit.value = true
    }
  }
  catch (err) {
    console.error('支付宝支付异常:', err)
    msg.value = '请求失败，请稍后再试'
    isSubmit.value = true
  }
  finally {
    isPaying.value = false
  }
}
onMounted(async () => {
  checkDevice()
  const { money: m, date: d, oid: o } = route.query
  if (!m || !d || !o) {
    msg.value = '缺少必要参数，无法发起支付'
    isSubmit.value = true
    return
  }
  money.value = route.query.money
  date.value = route.query.date
  orderId.value = String(route.query.oid)
  const { data: res } = await useFetchPost('/api/orders/getOrderInfo', {
    oid: route.query.oid,
  })
  if (res.value.data.status == 1) {
    msg.value = '祈福成功'
    isSubmit.value = true
    flag.value = true
  }
})
// 关闭弹窗
function closeModal() {
  isSubmit.value = false
  showQRCodeModal.value = false
  isPaying.value = false
  showPay.value = false
}

// function closePayModal() {
//   showPay.value = false
// }

const isLoading = ref(false)
</script>

<template>
  <div class="min-h-screen w-full relative">
    <Header back="/qifu" />
    <!-- 自适应背景图 -->
    <img
      src="/assets/images/qifu/zhifuye.png"
      alt=""
      class="h-auto w-full object-contain"
    >
    <div class="w-[35%] cursor-pointer right-[5%] top-[5%] absolute z-5" @click="router.push('/qifu')">
      <img
        src="/assets/images/qifu/back-date.png"
        alt=""
        class="h-auto w-full object-contain"
      >
    </div>
    <div class="text-xl text-[#fdf4d7] mx-auto w-[55%] bottom-[45%] left-0 right-0 absolute z-2">
      <span v-if="!flag">待您支付后，</span>我们将于{{ date }}在孔雀宫代您祈福。
    </div>
    <div v-if="!flag" class="flex w-full bottom-[25%] justify-center absolute z-1">
      <button :disabled="isLoading" class="opacity-90 w-[150px] cursor-pointer transition-opacity hover:opacity-100 md:w-[170px]" @click="showPay = true">
        <img
          src="/assets/images/qifu/pay-button.png"
          alt=""
        >
      </button>
    </div>
    <!-- <div
        v-if="showPopup"
        class="fixed inset-0 flex flex-col items-center justify-between bg-black bg-opacity-50 z-5"
        >
        <div class="flex-grow flex flex-col items-center justify-center max-w-9/10 max-h-9/10">
            <div class="relative">
                <img
                src="/assets/images/qifu/success.png"
                alt="成功图标"
                />
                <img
                src="/assets/images/qifu/submit.png"
                alt="确认按钮"
                class="absolute bottom-[15%] left-1/2 -translate-x-1/2 w-[120px] cursor-pointer"
                @click="showPopup = false"
                />
            </div>
        </div>
    </div> -->

    <div
      v-if="showPay"
      class="mx-auto opacity-0 flex w-full delay-[100ms] items-center inset-0 left-0 right-0 justify-center fixed z-2 animate-fade-in-up md:w-1/2"
    >
      <div class="mx-auto bg-black bg-opacity-50 w-full inset-0 left-0 right-0 fixed md:w-[90%]" @click="closeModal" />
      <div class="mx-auto w-[80%] left-0 right-0 relative">
        <img
          src="/assets/images/fengshui/border-pay.png"
          alt=""
          class="w-full object-contain"
        >
        <!-- 蒙版层 -->
        <!-- 中间内容叠加展示 -->
        <div class="top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/3 w-[90%] absolute">
          <div class="flex flex-col gap-3 items-center">
            <div class="p-4 pb-3 border-b border-gray-500 flex items-center justify-between" @click="submitPayWx">
              <div class="w-[30%]">
                <img
                  src="/assets/images/wx-icon.png"
                  alt=""
                  class="h-auto w-full object-contain"
                >
              </div>
              <div class="w-[30%]">
                <img
                  src="/assets/images/wx-bt.png"
                  class="h-auto w-full object-contain"
                >
              </div>
            </div>
            <div v-if="!isWeChat()" class="p-4 flex items-center justify-between" @click="submitPayZfb">
              <div class="w-[30%]">
                <img
                  src="/assets/images/zfb-icon.png"
                  class="h-auto w-full object-contain"
                >
              </div>
              <div class="w-[30%]">
                <img
                  src="/assets/images/zfb-bt.png"
                  class="h-auto w-full object-contain"
                >
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <TipModal
      v-model="isSubmit"
      title="提示"
      :message="msg"
      @close="closeModal"
    />
    <TipModal
      v-model="showQRCodeModal"
      title="提示"
      message="请打开微信扫码支付"
      :image="qrCodeUrl"
      @close="closeModal"
    />
  </div>
</template>

<style scoped>
/* 自定义淡入上升动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 注册Tailwind动画 */
.animate-fade-in-up {
  animation: fadeInUp 0.1s ease-out forwards;
}

/* 定义延迟类 */
.delay-\[100ms\] {
  animation-delay: 100ms;
}

.glow-text {
  text-shadow: 0 0 8px rgba(255, 215, 0, 1);
}

img {
  transition:
    transform 0.3s ease,
    opacity 0.3s ease;
}

/* 确保截图区域可见 */
/* .image-container {
      width: 100%;
      height: 100%;
    } */

/* 隐藏非活动项（提升截图性能） */
.carousel-item:not(.active) {
  display: none;
}

.writing-vertical {
  writing-mode: vertical-rl;
  text-orientation: upright;
  letter-spacing: 0.1em;
  line-height: 1.4;
}
</style>
